import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ljy_p_app/config/config.dart';
import 'package:ljy_p_app/constans/lj_constans.dart';
import 'package:ljy_p_app/diffwidget/animated_background.dart';
import 'package:ljy_p_app/diffwidget/ljy_flex_button.dart';
import 'package:ljy_p_app/diffwidget/toast.dart';
import 'package:ljy_p_app/inputwidget/ljy_input_widget.dart';
import 'package:ljy_p_app/local/local_storage.dart';
import 'package:ljy_p_app/localization/localization_key.dart';
import 'package:ljy_p_app/particle/particle_widget.dart';
import 'package:ljy_p_app/routes/lj_routes.dart';
import 'package:ljy_p_app/style/lj_style.dart';
import 'package:ljy_p_app/utils/common_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LjLoginPage extends StatefulWidget {
  const LjLoginPage({super.key});

  @override
  State<LjLoginPage> createState() => _LjLoginPageState();
}

class _LjLoginPageState extends State<LjLoginPage> with LoginBloc {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // 触摸收起键盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        body: Stack(
          children: [
            // 用于在 Stack 中占据整个可用空间。它会将其子 widget 填充到 Stack 的所有边界
            Positioned.fill(child: AnimatedBackground()),
            Positioned.fill(child: ParticleWidget(30)),
            Center(
              /// 防止overflow现象
              child: SafeArea(
                /// 同时弹出键盘不遮挡
                child: SingleChildScrollView(
                  child: Card(
                    margin: EdgeInsets.symmetric(horizontal: 30.0),
                    elevation: 5,
                    color: LJColors.cardWhite,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10.0))),
                    child: Padding(
                      padding: EdgeInsets.only(
                          left: 30.0, top: 40.0, right: 30.0, bottom: 0.0),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Image(
                            image: AssetImage(LJICons.DEFAULT_USER_ICON),
                            width: 90,
                            height: 90,
                          ),
                          SizedBox(height: 20.0),
                          LjyInputWidget(
                            hintText: LocalizationKey.loginUsernameHintText.tr,
                            iconData: LJICons.LOGIN_USER,
                            onChanged: (String value) {
                              _userName = value;
                            },
                            controller: userController,
                          ),
                          SizedBox(height: 20.0),
                          LjyInputWidget(
                            hintText: LocalizationKey.loginPasswordHintText.tr,
                            iconData: LJICons.LOGIN_PW,
                            onChanged: (String value) {
                              _password = value;
                            },
                            controller: pwController,
                          ),
                          SizedBox(height: 20.0),
                          SizedBox(
                            height: 50,
                            child: Row(
                              children: [
                                Expanded(
                                  child: LjyFlexButton(
                                    text: LocalizationKey.loginText.tr,
                                    color: Theme.of(context).primaryColor,
                                    textColor: LJColors.textWhite,
                                    fontsize: 16,
                                    onPress: loginIn,
                                  ),
                                ),
                                SizedBox(
                                  width: 10,
                                ),
                                Expanded(
                                  child: LjyFlexButton(
                                    text: LocalizationKey.oauthText.tr,
                                    color: Theme.of(context).primaryColor,
                                    textColor: LJColors.textWhite,
                                    fontsize: 16,
                                    onPress: oauthLogin,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(height: 30.0),
                          InkWell(
                            child: Text(
                              LocalizationKey.switchLanguage.tr,
                              style: TextStyle(color: LJColors.mainTextColor),
                            ),
                            onTap: () {
                              CommonUtils.showLanguageDialog(context);
                            },
                          ),
                          SizedBox(height: 30.0)
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
            Center(
              child: Obx(() {
                return _isLoading.value
                    ? CircularProgressIndicator()
                    : SizedBox.shrink();
              }),
            )
          ],
        ),
      ),
    );
  }
}

mixin LoginBloc on State<LjLoginPage> {
  final TextEditingController userController = TextEditingController();

  final TextEditingController pwController = TextEditingController();

  String? _userName = "";

  String? _password = "";

  final _isLoading = false.obs;

  @override
  void initState() {
    super.initState();
    initParams();
  }

  initParams() async {
    _userName = await LocalStorage.get(Config.USER_NAME_KEY);
    _password = await LocalStorage.get(Config.PW_KEY);
    userController.value = TextEditingValue(text: _userName ?? '');
    pwController.value = TextEditingValue(text: _password ?? '');
  }

  @override
  void dispose() {
    super.dispose();
    userController.removeListener(_usernameChange);
    pwController.removeListener(_passwordChange);
  }

  _usernameChange() {
    _userName = userController.text;
  }

  _passwordChange() {
    _password = pwController.text;
  }

  loginIn() {
    commonLogin();
  }

  oauthLogin() {
    commonLogin();
  }

  commonLogin() async {
    if ((GetUtils.isNullOrBlank(_userName) ?? true) ||
        (GetUtils.isNullOrBlank(_password) ?? true)) {
      showTextToast('请输入用户名和密码');
      return;
    }
    if (!GetUtils.isPhoneNumber(_userName ?? '')) {
      showTextToast('用户名请输入正确的手机号');
      return;
    }

    _isLoading.value = true;

    /// 存储
    LocalStorage.save(Config.USER_NAME_KEY, _userName);
    LocalStorage.save(Config.PW_KEY, _password);

    await Future.delayed(Duration(seconds: 2));

    _isLoading.value = false;

    Get.snackbar('登录成功', '欢迎回来!!!');

    loginSuccess();
  }

  void loginSuccess() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setBool(LjConstans.isLoginKey, true);

    /// 已登录
    Get.offAllNamed(LjRoutes.home);
  }
}
